package org.university.util;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.university.dto.request.PageRequestParams;
import org.university.enums.GlobalEnums;

/**
 * @Author ：3570023082@qq.com
 * @Date ：2025/9/11 23:26
 * @Description ：For study.
 */
@Component
public class GlobalUtil {

    // 构建分页请求
    public Pageable buildPageRequest(PageRequestParams params) {
        if (!StringUtils.hasText(params.sort())) {
            return PageRequest.of(params.page(), params.size());
        }

        String[] sortParams = params.sort().split(",");
        if (sortParams.length != 2) {
            throw new IllegalArgumentException("排序参数格式错误，应为 '字段,方向'（如 'studentName,ASC'）");
        }

        String field = sortParams[0];
        String direction = sortParams[1];

        if (!params.allowedFields().contains(field)) {
            throw new IllegalArgumentException("无效的排序字段: " + field);
        }

        return PageRequest.of(
                params.page(),
                params.size(),
                Sort.by(Sort.Direction.fromString(direction), field)
        );
    }

    // 验证性别参数
    public void validateGender(String gender) {
        if (StringUtils.hasText(gender)) {
            try {
                GlobalEnums.Gender.valueOf(gender);
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("无效的性别值，应为 '男' 或 '女'");
            }
        }
    }
}
